import react from '@vitejs/plugin-react'
import { resolve } from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
import { defineConfig, loadEnv } from 'vite'
import viteCompression from 'vite-plugin-compression'
import { viteMockServe } from 'vite-plugin-mock'

/** 👇 https://vite.dev/config/ 👇 */
export default defineConfig((envConfig) => {
  const env = loadEnv(envConfig.mode, __dirname)
  return {
    /** 👇 打包优化 👇 */
    build: {
      minify: 'terser',
      /** 👇 生产环境时移除 console 和 debugger 👇 */
      terserOptions: { compress: { drop_console: true, drop_debugger: true } },
      rollupOptions: {
        /** 👇 修改不同功能文件的存放路径 👇 */
        output: {
          entryFileNames: 'js/[name]_[hash].js',
          chunkFileNames: 'js/[name]_[hash].js',
          assetFileNames: '[ext]/[name]_[hash].[ext]',

          manualChunks: {
            components: ['@ant-design/icons', '@loadable/component', 'mac-scrollbar'],
            echarts: ['echarts', 'echarts-for-react'],
            react: [
              'react',
              'react-dom',
              'react-compiler-runtime',
              'react-hot-toast',
              'react-router-dom',
              'zustand',
            ],
            utils: ['axios', 'crypto-js', 'dayjs', 'js-cookie', 'lodash', 'pixiu-number-toolkit'],
          },
        },
      },
    },
    /** 👇 插件 👇 */
    plugins: [
      react({ babel: { plugins: [['babel-plugin-react-compiler', { target: '18' }]] } }),
      /** 👇 本地 Mock 配置 👇 */
      viteMockServe({
        mockPath: 'mock',
        logger: envConfig.mode === 'development',
        enable: envConfig.mode === 'development',
        watchFiles: envConfig.mode === 'development',
      }),
      /** 👇 打包分析 👇 */
      visualizer({
        open: false,
        gzipSize: true,
        brotliSize: true,
        filename: 'bundleAnalyzerReport.html',
      }),
      /** 👇 代码压缩; 开启删除源文件后, 本地无法预览, 请慎重开启删除源文件 !!! 👇 */
      viteCompression({ deleteOriginFile: false, disable: envConfig.command !== 'build' }),
    ],
    /** 👇 路径 👇 */
    resolve: { alias: { '@': resolve(__dirname, './src') } },
    /** 👇 开发配置 👇 */
    server: {
      port: +env.VITE_PORT, // 将 string 转成 number
      /** 👇 代理跨域 👇 */
      proxy: {
        [env.VITE_SERVER_BASE_URI]: {
          /** 👇 允许跨域 👇 */
          changeOrigin: true,
          /** 👇 转发地址 👇 */
          target: `${env.VITE_SERVER_IP}:${env.VITE_SERVER_PORT}`,
          /** 👇 路径重写 👇 */
          rewrite: (path) => path.replace(new RegExp(`^${env.VITE_SERVER_BASE_URI}`), ''),
        },
      },
    },
  }
})
